package com.chinamobile.websocket.websocketdispatcher.distributor;

import cn.hutool.core.util.ObjectUtil;
import com.chinamobile.websocket.domain.dto.MessageDto;
import com.chinamobile.websocket.websocket.cache.EndpointCache;
import com.chinamobile.websocket.websocket.endpoint.WebSocketEndpointHandler;
import org.apache.commons.lang3.StringUtils;

import java.util.stream.Collectors;

/**
 * @className: AbstractMessageDistributor
 * @description 消息分发器抽象类
 * @author: fanzhijun
 * @date: 2024/1/22
 **/
public abstract class AbstractMessageDistributor<T extends MessageDto> implements MessageDistributor<T> {
    @Override
    public void doSend(MessageDto messageDto) {
        Integer type = messageDto.getType();
        if (type == null) {
            return;
        }
        if (StringUtils.isNotBlank(messageDto.getUniKey())) {
            // 单播 一对一
            WebSocketEndpointHandler endpoint = EndpointCache.getEndpoint(type, messageDto.getUniKey());
            if (endpoint != null) {
                endpoint.sendMessage(messageDto);
            }
            return;
        }
        // 筛选出所有连接的节点
        // 类似广播
        EndpointCache.getEndpointMap()
                .values()
                .stream()
                .filter(endpoint -> ObjectUtil.equal(type, endpoint.getType()))
                .collect(Collectors.toList())
                .forEach(endpoint -> {
                    endpoint.sendMessage(messageDto);
                });
    }

}
